package com.lagou.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lagou.utils.Constant;
import com.lagou.bean.Result;
import com.lagou.pojo.HotPosition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * @author senyang
 */
@Service
public class RedisCacheService {


    @Value("${default.pageNo}")
    Integer defaultPageNo;

    @Value("${default.pageSize}")
    Integer defaultPageSize;

    @Autowired
    JedisService jedisService;

    @Autowired
    HotPositionService hotPositionService;


    /**
     * 从Redis获取缓存，如果缓存不存在则查询mysql数据源，将结果方法缓存中
     * @return
     */
    public Result getHotPosRedisCache(){
        String redisCache = jedisService.get(Constant.HOT_POSITION_KEY);
        if(StringUtils.isEmpty(redisCache)){
            System.out.println(">>>>>>>>>>>>>>>   redis cache 未获取到热门职位缓存，开始去mysql直接查询热门职位   >>>>>>>>>>>>>>>");
            Page<HotPosition> all = hotPositionService.findAll(defaultPageNo, defaultPageSize);
            if(!CollectionUtils.isEmpty(all.getContent())){
                setRedisCache(Constant.HOT_POSITION_KEY, JSON.toJSONString(all),Constant.HOT_POSITION_KEY_EXPIRE);
            }
            return Result.ok(all);
        }
        System.out.println(">>>>>>>>>>>>>>>   redis cache 获取到了热门职位缓存，直接返回了   >>>>>>>>>>>>>>>");
        JSONObject  obj = (JSONObject) JSONObject.parse(redisCache);
        return Result.ok(obj);
    }


    public Result setRedisCache(String key,String value,int expire){
        System.out.println(">>>>>>>>>>>>>>>   查询完mysql后，开始设置 redis cache  >>>>>>>>>>>>>>>");
        jedisService.set(key,value,expire + expire);
        return Result.ok();
    }


    public void removeRedisCache(String key){
        jedisService.delKey(key);
    }
}
